package com.vcarecity.api;

import com.alibaba.fastjson.JSONObject;
import com.vcarecity.base.BaseApiService;
import com.vcarecity.base.ResponseBase;
import com.vcarecity.entity.AppEntity;
import com.vcarecity.mapper.AppMapper;
import com.vcarecity.base.BaseRedisService;
import com.vcarecity.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/auth")
public class AuthController extends BaseApiService {
    //令牌 仅保存7天
    //private final long TimeOut = 60*60*24*7l;
    //令牌 仅保存2小时
    //private final long TimeOut = 60 * 60 * 2l;
    //令牌 仅保存2分钟
    //private final long TimeOut = 60 * 2l;
    @Value("${token.expires_in}")
    private long TimeOut;

    @Resource
    private AppMapper appMapper;
    @Autowired
    private BaseRedisService redisService;

    @RequestMapping("/getAccessToken")
    public ResponseBase getAccessToken(AppEntity appEntity) {
        //1.获取生成对应的appid和appSecret  验证是否有效
        AppEntity app = appMapper.findApp(appEntity);
        if (app == null) {
            return setResultError("没有该机构信息，请联系客服。");
        }
        int isFlag = app.getIsFlag();
        if (isFlag == 1) {
            return setResultError("未对该机构开放权限,请联系客服。");
        }

        //2.删除之前的accessToken，保证第二步与第三步在同一事务中
        String oldAccessToken = app.getAccessToken();
        if (!StringUtils.isEmpty(oldAccessToken)) {  //判断accessToken 是否为空，如果不为空 删除之前的token
            redisService.delKey(oldAccessToken);
        }
        //3.使用Appid和appSecret生成token，保证生成唯一的AccessToken
        String accessToken = TokenUtils.getAccessToken(app.getAppId(),app.getAppSecret());
        redisService.setString(accessToken, app.getAppId(), TimeOut);//存放数据到redis中
        String redisAppId = redisService.getString(accessToken);
        System.out.println("redisAppId:"+redisAppId);
        appMapper.updateAccessToken(accessToken, app.getAppId());
        //4.返回最新的accessToken
        JSONObject data = new JSONObject();
        data.put("accessToken", accessToken);
        data.put("expires_in", TimeOut);
        return setResultSuccessData(data);
    }

    @RequestMapping("/test")
    public String test() {
        return "测试成功!";
    }
    @RequestMapping("/signOut")
    public String signOut(String accessToken) {
        redisService.delKey(accessToken);
        return "签出成功!";
    }
}
